package master选举.curator实现;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
import org.apache.curator.retry.RetryNTimes;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

/**
 * author Veng Su
 * email  1344114844@qq.com
 * date   18-9-18 下午11:27
 */
//leader latch 需要手动close() 或者 客户端断开链接时就会释放master节点，此节点就不能再参与选举，除非重新注册一个latch
public class ZKLeaderUtils {
    private static String KEY_LEADER_PATH = "/test";

    public static void main(String[] args) throws Exception {
        List<LeaderLatch> list = new ArrayList<>();
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        final List<CuratorFramework> clients = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            CuratorFramework curatorClient = CuratorFrameworkFactory.newClient("192.168.0.201:2181,192.168.0.203:2181,192.168.0.204:2181", 60 * 1000, 30 * 1000,
                    new RetryNTimes(3, 1000));
            curatorClient.start();
            final LeaderLatch leaderLatch = new LeaderLatch(curatorClient, KEY_LEADER_PATH, String.valueOf(i));
            leaderLatch.addListener(new LeaderLatchListener() {
                @Override
                public void isLeader() {
                    System.out.println(leaderLatch.getId() + ":I am leader. I am doing jobs!");
                }

                @Override
                public void notLeader() {
                    System.out.println(leaderLatch.getId() + ":I am not leader. I will do nothing!");
                }
            });
            leaderLatch.start();
            list.add(leaderLatch);
            clients.add(curatorClient);
        }
        //模拟出现4次故障
        for (int i = 0; i < 4; i++) {
            Thread.sleep(2000);
            System.out.println("出现故障");
            //出现故障则手动close
            for (LeaderLatch leaderLatch : list) {
                if (leaderLatch.hasLeadership()) {//这个hasleadership是判断当前节点是否是主节点
                    leaderLatch.close();
                }
            }
        }

//当故障超过可以选举的节点的时候，这时，服务就不可用了
        System.out.println("sleep");
        Thread.sleep(10000);
    }
}